package com.lun.swordtowardoffer2.c04;

import com.lun.util.SinglyLinkedList.ListNode;

public class AddTwoNumbers {

	private static final ReverseList RL = new ReverseList();
	
	public ListNode addTwoNumbers(ListNode head1, ListNode head2) {
		head1 = RL.reverseList(head1);
		head2 = RL.reverseList(head2);
		return RL.reverseList(addReversed(head1, head2));
	}

	private ListNode addReversed(ListNode head1, ListNode head2) {
		ListNode result = null, last = null;
		int carry = 0;
		
		while(head1 != null || head2 != null || carry > 0) {
			
			int num1 = head1 == null ? 0 : head1.val;
			int num2 = head2 == null ? 0 : head2.val;
			
			int sum = num1 + num2 + carry;
			carry = sum / 10;
			
			ListNode temp = new ListNode(sum - carry * 10);
			
			if(last == null) {
				last = result = temp;
			}else {
				last.next = temp;
				last = last.next;
			}
			
			if(head1 != null)
				head1 = head1.next;
			
			if(head2 != null)
				head2 = head2.next;
		}
		
		return result;
	}
	
}
